package yb.ecp.fast.user.web;

import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.user.infra.AuthCode;
import yb.ecp.fast.user.infra.BasicController;
import yb.ecp.fast.user.infra.ErrorCode;
import yb.ecp.fast.user.service.AccountService;
import yb.ecp.fast.user.service.AuthService;
import yb.ecp.fast.user.service.UserContextService;
import yb.ecp.fast.user.service.VO.PasswordResetVO;
import yb.ecp.fast.user.service.VO.UpdatePasswordVO;
import yb.ecp.fast.user.service.VO.UserLoginVO;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * Created by john on 2017/10/18.
 */
@RestController
@RequestMapping("/auth")
public class AuthController extends BasicController {
    @Autowired
    UserContextService userContextService;
    @Autowired
    AccountService accountService;
    @Autowired
    AuthService authService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ActionResult<String> login(@RequestBody UserLoginVO userLoginVO, @RequestHeader("x-from-site") Integer site, HttpServletRequest request) throws Exception {
        //        System.out.println("from outside " + userLoginVO.toString());
        //如果登录成功，只返回userid,所有的其他信息使用其他接口来获取。session里只存储user-id
        Ref<String> userIdRef = new Ref<String>("");
        ErrorCode ret = accountService.login(userLoginVO, userIdRef, site, request, 1);
        return actionResult(ret, userIdRef.get());
    }

    @RequestMapping(value = "/loginWithoutVerifyCode", method = RequestMethod.POST)
    public ActionResult loginWithoutVerifyCode(@RequestBody UserLoginVO userLoginVO, @RequestHeader("x-from-site") Integer site) throws Exception {
        //        System.out.println("from outside " + userLoginVO.toString());
        //如果登录成功，只返回userid,所有的其他信息使用其他接口来获取。session里只存储user-id
        Ref<String> userIdRef = new Ref<String>("");
        ErrorCode ret = accountService.loginWithoutVerifyCode(userLoginVO, userIdRef, site);
        return actionResult(ret, userIdRef.get());
    }


    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public ActionResult login(@RequestParam("loginName") String loginName, @RequestParam("password") String password, @RequestParam("authId") String authId, @RequestParam("code") String code, @RequestHeader("x-from-site") Integer site, HttpServletRequest request) throws Exception {

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setAuthId(authId);
        userLoginVO.setCode(code);
        userLoginVO.setLoginName(loginName);
        userLoginVO.setPassword(password);

        //如果登录成功，只返回userid,所有的其他信息使用其他接口来获取。session里只存储user-id
        Ref<String> userIdRef = new Ref<String>("");
        ErrorCode ret = accountService.login(userLoginVO, userIdRef, site, request, null);
        return actionResult(ret, userIdRef.get());
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult logout(@RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtil.isEmpty(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        userContextService.clearSession(userId);
        return actionResult(userId);
    }

    @RequestMapping(value = "/authInfo", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = false)
    public ActionResult authInfo() {
        return actionResult(authService.createAuthInfo());
    }

    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = false)
    public void kaptcharImg(@RequestParam("authid") String authId, HttpServletResponse httpServletResponse) throws Exception {

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        BufferedImage verifyImg = authService.createVerifyImg(authId);
        ImageIO.write(verifyImg, "jpg", jpegOutputStream);

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @RequestMapping(value = "/password", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult password(@RequestHeader("x-user-id") String userId, @RequestBody UpdatePasswordVO updatePasswordVO) throws Exception {
        if (StringUtil.isEmpty(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        ErrorCode ret = accountService.updatePassword(userId, updatePasswordVO);
        return actionResult(ret);
    }

    /**
     * @Des 用户名密码方式修改登录密码
     * @Date 2021/4/25 10:55
     * @Author wangzhaoyu
     * @Param [passwordReset]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @RequestMapping(value = "/passwordModify", method = RequestMethod.POST)
    public ActionResult passWordModify(@RequestBody PasswordResetVO passwordReset) {
        try {
            ErrorCode errorCode = accountService.modifyPassword(passwordReset);
            return actionResult(errorCode);
        } catch (Exception e) {
            return actionResult(ErrorCode.ModifyPwdFail);
        }
    }

    @GetMapping(value = "/resetAdminPasswordByOrgId")
    @FastMappingInfo(needLogin = true, code = AuthCode.Account.RESET_PASSWORD_BY_ORG)
    public ActionResult resetAdminPasswordByOrgId(@RequestParam("orgId") String orgId) {
        accountService.resetAdminPasswordByOrgId(orgId);
        return actionResult(ErrorCode.Success);
    }
}
